# add_card.py
import random

from aaa.api.base_api import BaseAPI
from aaa.utils.DB import DB


class AddCard(BaseAPI):

    def add_card(self, data_add_card):
        url_add_card = f'{self.BASE_URL}/user/addBankCard'
        response = self.session.post(url_add_card, data=data_add_card)
        return self._handle_response(response, '添加银行卡')

    #  选中默认银行卡
    def select_default_card(self, data_login):
        username = data_login.get('username')
        db = DB()
        db.connect()
        user_id = db.execute(
            "SELECT id FROM user WHERE username = %s",
            (username,)
        )
        result = db.execute('select id,defaultl from bankcard where userId = %s', (user_id,))
        card_id = [item[0] for item in result if item[1] == 0]
        selected_id = 0
        if card_id:
            selected_id = random.choice(card_id)
            print(selected_id)  # 随机选择一个未激活的 id
        else:
            print("没有未激活的银行卡")
        db.close()
        #
        url_default_card = f'{self.BASE_URL}/user/personal/toBankCardDefault.html/{selected_id} '
        response = self.session.post(url_default_card)
        return self._handle_response(response, '选中默认银行卡')


if __name__ == '__main__':
    add_card = AddCard()
    data_login = {
        'username': 'user',
        'password': 'e10adc3949ba59abbe56e057f20f883e',
    }
    add_card.select_default_card(data_login)
